package com.sxc.oa.web.action;

import com.sxc.oa.utils.DButil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/user/register")
public class RegisterServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean success = false;

        // 获取注册信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        // 连接数据库并插入新用户
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DButil.getConnction();
            String sql = "INSERT INTO t_user (username, password) VALUES (?, ?)";

            // 编译SQL
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);

            int rows = ps.executeUpdate();
            if (rows > 0) {
                // 注册成功
                success = true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                DButil.close(conn, ps, null);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        // 根据注册结果进行跳转
        if (success) {
            response.sendRedirect(request.getContextPath() + "/index.html");
        } else {
            response.sendRedirect(request.getContextPath() + "/error.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
